import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:shared_preferences/shared_preferences.dart';

class StorageService {
  static const FlutterSecureStorage _secureStorage = FlutterSecureStorage(
    aOptions: AndroidOptions(
      encryptedSharedPreferences: true,
    ),
    iOptions: IOSOptions(
      accessibility: KeychainItem.first_unlock_this_device,
    ),
  );
  
  static late SharedPreferences _prefs;

  static Future<void> init() async {
    _prefs = await SharedPreferences.getInstance();
  }

  // Token Management
  static Future<void> saveToken(String token) async {
    await _secureStorage.write(key: 'auth_token', value: token);
    await _prefs.setString('auth_token', token);
  }

  static Future<String?> getToken() async {
    // 首先尝试从安全存储获取
    String? token = await _secureStorage.read(key: 'auth_token');
    
    // 如果安全存储中没有，尝试从SharedPreferences获取
    if (token == null) {
      token = _prefs.getString('auth_token');
      // 如果SharedPreferences中有，迁移到安全存储
      if (token != null) {
        await saveToken(token);
      }
    }
    
    return token;
  }

  static Future<void> clearToken() async {
    await _secureStorage.delete(key: 'auth_token');
    await _prefs.remove('auth_token');
  }

  // User Preferences
  static Future<void> saveUserPreferences(Map<String, dynamic> preferences) async {
    for (var entry in preferences.entries) {
      switch (entry.value.runtimeType) {
        case String:
          await _prefs.setString(entry.key, entry.value);
          break;
        case int:
          await _prefs.setInt(entry.key, entry.value);
          break;
        case bool:
          await _prefs.setBool(entry.key, entry.value);
          break;
        case double:
          await _prefs.setDouble(entry.key, entry.value);
          break;
        case List:
          await _prefs.setStringList(entry.key, List<String>.from(entry.value));
          break;
      }
    }
  }

  static dynamic getUserPreference(String key) {
    return _prefs.get(key);
  }

  static Future<void> removeUserPreference(String key) async {
    await _prefs.remove(key);
  }

  // App Settings
  static Future<void> setDarkMode(bool enabled) async {
    await _prefs.setBool('dark_mode', enabled);
  }

  static bool isDarkMode() {
    return _prefs.getBool('dark_mode') ?? false;
  }

  static Future<void> setLanguage(String languageCode) async {
    await _prefs.setString('language', languageCode);
  }

  static String getLanguage() {
    return _prefs.getString('language') ?? 'zh';
  }

  static Future<void> setNotificationEnabled(bool enabled) async {
    await _prefs.setBool('notifications_enabled', enabled);
  }

  static bool isNotificationEnabled() {
    return _prefs.getBool('notifications_enabled') ?? true;
  }

  // Cache Management
  static Future<void> setCache(String key, String value, {Duration? expiration}) async {
    await _prefs.setString('cache_$key', value);
    
    if (expiration != null) {
      final expiryTime = DateTime.now().add(expiration).millisecondsSinceEpoch;
      await _prefs.setInt('cache_expiry_$key', expiryTime);
    }
  }

  static String? getCache(String key) {
    final expiryTime = _prefs.getInt('cache_expiry_$key');
    
    if (expiryTime != null) {
      final now = DateTime.now().millisecondsSinceEpoch;
      if (now > expiryTime) {
        // Cache expired
        _prefs.remove('cache_$key');
        _prefs.remove('cache_expiry_$key');
        return null;
      }
    }
    
    return _prefs.getString('cache_$key');
  }

  static Future<void> clearCache() async {
    final keys = _prefs.getKeys();
    for (var key in keys) {
      if (key.startsWith('cache_')) {
        await _prefs.remove(key);
      }
    }
  }

  // Search History
  static Future<void> addSearchHistory(String query) async {
    final history = getSearchHistory();
    history.remove(query); // Remove if already exists
    history.insert(0, query); // Add to beginning
    
    // Keep only last 20 items
    if (history.length > 20) {
      history.removeRange(20, history.length);
    }
    
    await _prefs.setStringList('search_history', history);
  }

  static List<String> getSearchHistory() {
    return _prefs.getStringList('search_history') ?? [];
  }

  static Future<void> clearSearchHistory() async {
    await _prefs.remove('search_history');
  }

  // Recently Viewed
  static Future<void> addRecentlyViewed(int itemId, String itemType) async {
    final recentlyViewed = getRecentlyViewed();
    final item = '$itemType:$itemId';
    
    recentlyViewed.remove(item); // Remove if already exists
    recentlyViewed.insert(0, item); // Add to beginning
    
    // Keep only last 50 items
    if (recentlyViewed.length > 50) {
      recentlyViewed.removeRange(50, recentlyViewed.length);
    }
    
    await _prefs.setStringList('recently_viewed', recentlyViewed);
  }

  static List<String> getRecentlyViewed() {
    return _prefs.getStringList('recently_viewed') ?? [];
  }

  static Future<void> clearRecentlyViewed() async {
    await _prefs.remove('recently_viewed');
  }

  // Clear all data (for logout)
  static Future<void> clearAllData() async {
    await clearToken();
    await clearCache();
    await clearSearchHistory();
    await clearRecentlyViewed();
    
    // Keep some preferences
    final darkMode = isDarkMode();
    final language = getLanguage();
    final notificationsEnabled = isNotificationEnabled();
    
    await _prefs.clear();
    
    // Restore preferences
    await setDarkMode(darkMode);
    await setLanguage(language);
    await setNotificationEnabled(notificationsEnabled);
  }
}